{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **初步认识docx**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入库\n",
    "from docx import Document\n",
    "\n",
    "# 新建空白文档\n",
    "doc_1 = Document()\n",
    "\n",
    "# 添加标题（0相当于文章的题目，默认级别是1，级别范围为0-9）\n",
    "doc_1.add_heading('新建空白文档标题，级别为0',level = 0)\n",
    "doc_1.add_heading('新建空白文档标题，级别为1',level = 1)\n",
    "doc_1.add_heading('新建空白文档标题，级别为2',level = 2)\n",
    "\n",
    "# 新增段落\n",
    "paragraph_1 = doc_1.add_paragraph('这是第一段文字的开始\\n请多多关照！')\n",
    "# 加粗\n",
    "paragraph_1.add_run('加粗字体').bold = True\n",
    "paragraph_1.add_run('普通字体')\n",
    "# 斜体\n",
    "paragraph_1.add_run('斜体字体').italic =True\n",
    "\n",
    "# 新段落（当前段落的下方）\n",
    "paragraph_2 = doc_1.add_paragraph('新起的第二段文字。')\n",
    "\n",
    "# 新段落（指定端的上方）\n",
    "prior_paragraph = paragraph_1.insert_paragraph_before('在第一段文字前插入的段落')\n",
    "\n",
    "# 添加分页符(可以进行灵活的排版）\n",
    "doc_1.add_page_break()\n",
    "# 新段落（指定端的上方）\n",
    "paragraph_3 = doc_1.add_paragraph('这是第二页第一段文字！')\n",
    "\n",
    "# 保存文件（当前目录下）\n",
    "doc_1.save('doc_1.docx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **整体页面结构介绍**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "中国台湾华语流行歌手、音乐创作家、作曲家、作词人、制作人、杰威尔音乐公司老板之一、导演。近年涉足电影行业。周杰伦是2000年后亚洲流行乐坛最具革命性与指标性的创作歌手，有“亚洲流行天王”之称。他突破原有亚洲音乐的主题、形式，融合多元的音乐素材，创造出多变的歌曲风格，尤以融合中西式曲风的嘻哈或节奏蓝调最为著名，可说是开创华语流行音乐“中国风”的先声。周杰伦的出现打破了亚洲流行乐坛长年停滞不前的局面，为亚洲流行乐坛翻开了新的一页！\n"
     ]
    }
   ],
   "source": [
    "# 导入库\n",
    "from docx import Document\n",
    "from docx.shared import RGBColor, Pt,Inches,Cm\n",
    "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n",
    "from docx.oxml.ns import qn\n",
    "\n",
    "# 新建文档（Datawhale）\n",
    "doc_1 = Document()\n",
    "\n",
    "# 字体设置（全局）\n",
    "'''只更改font.name是不够的，还需要调用._element.rPr.rFonts的set()方法。'''\n",
    "\n",
    "doc_1.styles['Normal'].font.name = u'宋体'\n",
    "doc_1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')\n",
    "\n",
    "# 添加标题（0相当于文章的题目，默认级别是1，级别范围为0-9，0时候自动带下划线）\n",
    "#WD_ALIGN_PARAGRAPH. LEFT：左对齐；\n",
    "#WD_ALIGN_PARAGRAPH. CENTER：居中对其；\n",
    "#WD_ALIGN_PARAGRAPH. RIGHT：右对齐；\n",
    "#WD_ALIGN_PARAGRAPH. JUSTIFY：两端对齐；\n",
    "heading_1 = doc_1.add_heading('周杰伦',level = 0)\n",
    "heading_1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER   #居中对齐，默认居左对齐\n",
    "\n",
    "# 新增段落\n",
    "paragraph_1 = doc_1.add_paragraph()\n",
    "'''\n",
    "设置段落格式：首行缩进0.75cm，居左，段后距离1.0英寸,1.5倍行距。\n",
    "'''\n",
    "paragraph_1.paragraph_format.first_line_indent = Cm(0.75)\n",
    "paragraph_1.paragraph_format.alignment =  WD_PARAGRAPH_ALIGNMENT.LEFT\n",
    "paragraph_1.paragraph_format.space_after =  Inches(1.0)\n",
    "paragraph_1.paragraph_format.line_spacing =  1.5\n",
    "\n",
    "text = '中国台湾华语流行歌手、' \\\n",
    "       '音乐创作家、作曲家、作词人、' \\\n",
    "       '制作人、杰威尔音乐公司老板之一、导演。' \\\n",
    "       '近年涉足电影行业。周杰伦是2000年后亚洲流行乐坛最具革命性与指标' \\\n",
    "       '性的创作歌手，有“亚洲流行天王”之称。他突破原有亚洲音乐的主题、形' \\\n",
    "       '式，融合多元的音乐素材，创造出多变的歌曲风格，尤以融合中西式曲风的嘻哈' \\\n",
    "       '或节奏蓝调最为著名，可说是开创华语流行音乐“中国风”的先声。周杰伦的' \\\n",
    "       '出现打破了亚洲流行乐坛长年停滞不前的局面，为亚洲流行乐坛翻开了新的一页！'\n",
    "    \n",
    "r_1 = paragraph_1.add_run(text)\n",
    "r_1.font.size =Pt(10)    #字号\n",
    "r_1.font.bold =True       #加粗\n",
    "r_1.font.color.rgb =RGBColor(255,0,0)      #颜色\n",
    "\n",
    "print(len(paragraph_1.runs))    # 查看段落拥有的run对象数量\n",
    "print(paragraph_1.runs[0].text)  # 查看对应run对象的文本等属性\n",
    "\n",
    "# 保存文件（当前目录下）\n",
    "doc_1.save('周杰伦.docx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **字体设置**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''字体设置1.py'''\n",
    "#导入库\n",
    "from docx import Document\n",
    "from docx.oxml.ns import qn\n",
    "from docx.enum.style import WD_STYLE_TYPE\n",
    "\n",
    "document = Document() # 新建docx文档\n",
    "\n",
    "# 设置宋体字样式\n",
    "style_font = document.styles.add_style('宋体', WD_STYLE_TYPE.CHARACTER)\n",
    "style_font.font.name = '宋体'\n",
    "document.styles['宋体']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')\n",
    "\n",
    "# 设置楷体字样式\n",
    "style_font = document.styles.add_style('楷体', WD_STYLE_TYPE.CHARACTER)\n",
    "style_font.font.name = '楷体'\n",
    "document.styles['楷体']._element.rPr.rFonts.set(qn('w:eastAsia'), u'楷体')\n",
    "\n",
    "# 设置华文中宋字样式\n",
    "style_font = document.styles.add_style('华文中宋', WD_STYLE_TYPE.CHARACTER)\n",
    "style_font.font.name = '华文中宋'\n",
    "document.styles['华文中宋']._element.rPr.rFonts.set(qn('w:eastAsia'), u'华文中宋')\n",
    "\n",
    "paragraph1 = document.add_paragraph() # 添加段落\n",
    "run = paragraph1.add_run(u'aBCDefg这是中文', style='宋体') # 设置宋体样式\n",
    "\n",
    "font = run.font #设置字体\n",
    "font.name = 'Cambira' # 设置西文字体\n",
    "paragraph1.add_run(u'aBCDefg这是中文', style='楷体').font.name = 'Cambira'\n",
    "paragraph1.add_run(u'aBCDefg这是中文', style='华文中宋').font.name = 'Cambira'\n",
    "\n",
    "document.save('字体设置1.docx')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''字体设置2.py'''\n",
    "#导入库\n",
    "from docx import Document\n",
    "from docx.oxml.ns import qn\n",
    "from docx.enum.style import WD_STYLE_TYPE\n",
    "\n",
    "#定义字体设置函数\n",
    "def font_setting(doc,text,font_cn):\n",
    "       style_add = doc.styles.add_style(font_cn, WD_STYLE_TYPE.CHARACTER)\n",
    "       style_add.font.name = font_cn\n",
    "       doc.styles[font_cn]._element.rPr.rFonts.set(qn('w:eastAsia'), font_cn)\n",
    "       par = doc.add_paragraph()\n",
    "       text = par.add_run(text, style=font_cn)\n",
    "\n",
    "doc = Document()\n",
    "a = '小朋友 你是否有很多问号'\n",
    "b = '为什么 别人在那看漫画'\n",
    "c = '我却在学画画 对着钢琴说话'\n",
    "\n",
    "font_setting(doc,a,'宋体')\n",
    "font_setting(doc,b,'华文中宋')\n",
    "font_setting(doc,c,'黑体')\n",
    "\n",
    "doc.save('字体设置2.docx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **插入图片与表格**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "#导入库\n",
    "import docx\n",
    "from docx import Document\n",
    "from docx.shared import Inches\n",
    "\n",
    "#打开文档\n",
    "doc_1 = Document('周杰伦.docx')   #上面脚本存储的文档\n",
    "#新增图片\n",
    "doc_1.add_picture('周杰伦.jpg',width=Inches(1.0), height=Inches(1.0))\n",
    "\n",
    "# 创建3行1列表格\n",
    "table1 = doc_1.add_table(rows=2, cols=1)\n",
    "table1.style='Medium Grid 1 Accent 1'  #表格样式很多种，如，Light Shading Accent 1等\n",
    "\n",
    "# 修改第2行第3列单元格的内容为营口\n",
    "table1.cell(0, 0).text = '营口'\n",
    "# 修改第3行第4列单元格的内容为人民\n",
    "table1.rows[1].cells[0].text = '人民'\n",
    "\n",
    "# 在表格底部新增一行\n",
    "row_cells = table1.add_row().cells\n",
    "# 新增行的第一列添加内容\n",
    "row_cells[0].text = '加油'\n",
    "\n",
    "doc_1.save('周杰伦为营口加油.docx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **设置页眉页脚**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from docx import Document\n",
    "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n",
    "\n",
    "document = Document() # 新建文档\n",
    "\n",
    "header = document.sections[0].header # 获取第一个节的页眉\n",
    "print('页眉中默认段落数：', len(header.paragraphs))\n",
    "paragraph = header.paragraphs[0] # 获取页眉的第一个段落\n",
    "paragraph.add_run('这是第一节的页眉') # 添加页面内容\n",
    "footer = document.sections[0].footer # 获取第一个节的页脚\n",
    "paragraph = footer.paragraphs[0] # 获取页脚的第一个段落\n",
    "paragraph.add_run('这是第一节的页脚') # 添加页脚内容\n",
    "\n",
    "\n",
    "'''在docx文档中又添加了2个节，共计3个节，页面和页脚会显示了“与上一节相同”。\n",
    "如果不使用上一节的内容和样式要将header.is_linked_to_previous的属性或footer.is_linked_to_previous的属性设置为False，\n",
    "用于解除“链接上一节页眉”或者“链接上一节页脚”。'''\n",
    "document.add_section() # 添加一个新的节\n",
    "document.add_section() # 添加第3个节\n",
    "header = document.sections[1].header # 获取第2个节的页眉\n",
    "header.is_linked_to_previous = False # 不使用上节内容和样式\n",
    "\n",
    "#对齐设置\n",
    "header = document.sections[1].header # 获取第2个节的页眉\n",
    "header.is_linked_to_previous = False # 不使用上节内容和样式\n",
    "paragraph = header.paragraphs[0]\n",
    "paragraph.add_run('这是第二节的页眉')\n",
    "paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 设置页眉居中对齐\n",
    "document.sections[1].footer.is_linked_to_previous = False\n",
    "footer.paragraphs[0].add_run('这是第二节的页脚') # 添加第2节页脚内容\n",
    "footer.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 设置第2节页脚居中对齐\n",
    "header = document.sections[2].header # 获取第3个节的页眉\n",
    "header.is_linked_to_previous = False # 不使用上节的内容和样式\n",
    "paragraph = header.paragraphs[0] # 获取页眉中的段落\n",
    "paragraph.add_run('这是第三节的页眉')\n",
    "paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 设置页眉右对齐\n",
    "document.sections[2].footer.is_linked_to_previous = False\n",
    "footer.paragraphs[0].add_run('这是第三节的页脚') # 添加第3节页脚内容\n",
    "footer.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 设置第3节页脚右对齐\n",
    "document.save('页眉页脚1.docx') # 保存文档"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **项目实践**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入库\n",
    "from openpyxl import load_workbook\n",
    "from docx import Document\n",
    "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n",
    "from docx.shared import RGBColor, Pt,Inches,Cm\n",
    "from docx.oxml.ns import qn\n",
    "\n",
    "\n",
    "path = r'D:\\idea\\cloud_analyse_game_sentiment\\word自动化'\n",
    "# 路径为Excel 文件所在的位置，可按实际情况更改\n",
    "\n",
    "workbook = load_workbook(path + r'\\excel到word.xlsx')\n",
    "sheet = workbook.active   #默认的WorkSheet\n",
    "\n",
    "n = 0   #为了不遍历标题（excel的第一行）\n",
    "for row in sheet.rows:\n",
    "    if n:\n",
    "        company = row[0].value\n",
    "        office = row[1].value\n",
    "        name = row[2].value\n",
    "        date = str(row[3].value).split()[0]\n",
    "        print(company, office, name, date)\n",
    "\n",
    "\n",
    "        doc = Document()\n",
    "        heading_1 = '邀 请 函'\n",
    "        paragraph_1 = doc.add_heading(heading_1, level=1)\n",
    "        # 居中对齐\n",
    "        paragraph_1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n",
    "        # 单独修改较大字号\n",
    "        for run in paragraph_1.runs:\n",
    "            run.font.size = Pt(17)\n",
    "\n",
    "        greeting_word_1 = '尊敬的'\n",
    "        greeting_word_2 = '公司'\n",
    "        greeting_word_3 = '，您好：'\n",
    "        paragraph_2 = doc.add_paragraph()\n",
    "\n",
    "        paragraph_2.add_run(greeting_word_1)\n",
    "        r_1 = paragraph_2.add_run(company)\n",
    "        r_1.font.bold = True  # 加粗\n",
    "        r_1.font.underline = True    #下划线\n",
    "\n",
    "        paragraph_2.add_run(greeting_word_2)\n",
    "\n",
    "        r_2 = paragraph_2.add_run(office)\n",
    "        r_2.font.bold = True  # 加粗\n",
    "        r_2.font.underline = True    #下划线\n",
    "\n",
    "        r_3 = paragraph_2.add_run(name)\n",
    "        r_3.font.bold = True  # 加粗\n",
    "        r_3.font.underline = True    #下划线\n",
    "        paragraph_2.add_run(greeting_word_3)\n",
    "\n",
    "        paragraph_3 = doc.add_paragraph()\n",
    "        paragraph_3.add_run('现诚挚的邀请您于2021年10月27日参加DataWhale主办的享受开源2050活动，地点在北京鸟巢，希望您届时莅临参加。')\n",
    "        paragraph_3.paragraph_format.first_line_indent = Cm(0.75)\n",
    "        paragraph_3.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT\n",
    "        paragraph_3.paragraph_format.space_after = Inches(1.0)\n",
    "        paragraph_3.paragraph_format.line_spacing = 1.5\n",
    "\n",
    "        paragraph_4 = doc.add_paragraph()\n",
    "        date_word_1 = '邀请时间：'\n",
    "        paragraph_4.add_run(date_word_1)\n",
    "        paragraph_4.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT\n",
    "        sign_date = \"{}年{}月{}日\".format(date.split('-')[0], date.split('-')[1], date.split('-')[2])\n",
    "        paragraph_4.add_run(sign_date).underline = True\n",
    "        paragraph_4.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT\n",
    "        \n",
    "        #设置全文字体\n",
    "        for paragraph in doc.paragraphs:\n",
    "            for run in paragraph.runs:\n",
    "                run.font.color.rgb = RGBColor(0, 0, 0)\n",
    "                run.font.name = '楷体'\n",
    "                r = run._element.rPr.rFonts\n",
    "                r.set(qn('w:eastAsia'), '楷体')\n",
    "        doc.save(path + \"\\{}-邀请函.docx\".format(name))\n",
    "    n = n + 1"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
